﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
using System;
using System.Linq.Expressions;

namespace Yyyg.Models
{
    public static class DbSetExt
    {
        public static DbSqlQuery<TSource> In<TSource>(this DbSet<TSource> ts, string field, IEnumerable<string> ins) where TSource : class
        {
            var entity = ts.FirstOrDefault();
            if (entity == null) return null;
            string tbname = typeof(TSource).Name;
            StringBuilder builder = new StringBuilder();
            var insarr = ins.ToArray();
            for (int i = 0; i < insarr.Length; i++) builder.Append("\'" + insarr[i] + "\',");
            var sql = $"select * from {tbname} where {field} in ( {builder.ToString().TrimEnd(',')} )";
            return ts.SqlQuery(sql);
        }

        public static DbSqlQuery<TSource> In<TSource>(this DbSet<TSource> ts, string field, IEnumerable<int> ins) where TSource : class
        {
            var entity = ts.FirstOrDefault();
            if (entity == null) return null;
            string tbname = typeof(TSource).Name;
            StringBuilder builder = new StringBuilder();
            var insarr = ins.ToArray();
            for (int i = 0; i < insarr.Length; i++) builder.Append(insarr[i] + ",");
            var sql = $"select * from {tbname} where {field} in ( {builder.ToString().TrimEnd(',')} )";
            return ts.SqlQuery(sql);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <param name="que"></param>
        /// <param name="pindex">页索引(从1开始)</param>
        /// <param name="psize">页大小</param>
        /// <returns></returns>
        public static IQueryable<TSource> QueryPage<TSource>(this IQueryable<TSource> que, int pindex, int psize)
        {
            if (psize <= 0) throw new ApplicationException("分页大小不能小于或等于0");
            if (pindex <= 0) throw new ApplicationException("页码不能小于或等于0");
            return que.Skip((pindex - 1) * psize).Take(psize);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <param name="que"></param>
        /// <param name="pindex">页索引(从1开始)</param>
        /// <param name="psize">页大小</param>
        /// <param name="datanums">输出数据总数</param>
        /// <returns></returns>
        public static IQueryable<TSource> QueryPage<TSource>(this IQueryable<TSource> que, int pindex, int psize, out int datanums)
        {
            datanums = que.Count();
            return que.QueryPage(pindex, psize);
        }
    }
}
